import { h, render } from "preact";
import { useRef, useState } from "preact/hooks";
import css from "./index.scss?raw";
import { Header } from "./header";
import { HidePanel } from "./hidePanel";
import { PanelMode } from "./type";

function TPL() {
  const [hide, setHide] = useState(false);
  const [mode, setMode] = useState<PanelMode>("pc");
  const [ hideContent, setHideContent ] = useState('')
  const ifRef = useRef(null);
  const setUrl = (url: string) => {
    (ifRef.current as unknown as HTMLIFrameElement).src = url;
  };
  return (
    <>
      <div class={"view-panel"}>
        <Header
          setMode={() => setMode(mode === "pc" ? "mobile" : "pc")}
          setIfSrc={(url: string) => setUrl(url)}
          setHide={ () => setHide(true) }
        ></Header>
        <div class={`content-base ${ mode} ${hide ? 'hide': ''}`}>
          <iframe ref={ifRef}></iframe>
        </div>
        { hide ? <HidePanel content={ hideContent } setHide={ () => setHide(false) } change={ (txt:string) => setHideContent(txt) } /> : <div></div>}
      </div>
    </>
  );
}

class MyWebComponent extends HTMLElement {
  constructor() {
    super();
    // 初始化 Shadow DOM 并渲染 Preact 组件
    const shadow = this.attachShadow({ mode: "open" });
    const styleEl = document.createElement("style");
    styleEl.innerHTML = css;
    this.shadowRoot?.append(styleEl);
    render(h(TPL, {}), shadow);
  }
}

customElements.define("webview-panel", MyWebComponent);
